//
//  MyInfoViewController.m
//  SportSocial
//
//  Created by yull on 15/1/11.
//  Copyright (c) 2015年 yull. All rights reserved.
//

#import "MyInfoViewController.h"
#import "UIColor+MethodExt.h"
#import <UIImageView+WebCache.h>
#import "NSString+Size.h"
#import "UserNet.h"

@interface MyInfoViewController () <UITextFieldDelegate,UITextViewDelegate,UIActionSheetDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@property (nonatomic, strong) UIScrollView *infoScrollView;

@property (nonatomic, strong) UIImageView *headImageView;
@property (nonatomic, strong) UIButton *uploadIconButton;

@property (nonatomic, strong) UIView *addressView;
@property (nonatomic, strong) UIView *sexView;
@property (nonatomic, strong) UIView *signView;
@property (nonatomic, strong) UIView *weightView;
@property (nonatomic, strong) UIView *heightView;
@property (nonatomic, strong) NSMutableArray *contentViewArray;

@property (nonatomic, strong) UITextView *addressTextView;
@property (nonatomic, strong) UIImageView *sexImageView;
@property (nonatomic, strong) UITextView *signTextView;
@property (nonatomic, strong) UITextField *weightTextField;
@property (nonatomic, strong) UITextField *heightTextField;

@property (nonatomic, strong) UIButton *editButton;
@property (nonatomic, strong) UIButton *sexButton;

@property (nonatomic, assign) NSInteger sex;
@end

@implementation MyInfoViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.sex = [CurrentUser shareInstance].sex;
    
    [self initNaviBar];
    
    [self initScrollView];
    
    [self initContentView];
    
    [self updateUserValue];
    
    [self updateContentFrame];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onkeyboardChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onkeyboardHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)initNaviBar
{
    self.navigationItem.title = @"我的资料";
    
    [self addCommonBackButton];
}

- (void)initScrollView
{
    self.infoScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height - Navibar_Height)];
    [self.view addSubview:self.infoScrollView];
    
    UIImageView *backImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.infoScrollView.width, 190)];
    backImageView.image = [UIImage imageNamed:@"user_info_bg"];
    backImageView.userInteractionEnabled = YES;
    [self.infoScrollView addSubview:backImageView];
    
    CGRect rect = CGRectMake(0, 20, 80, 80);
    self.headImageView = [[UIImageView alloc] initWithFrame:rect];
    self.headImageView.centerX = backImageView.width/2;
    self.headImageView.layer.cornerRadius = rect.size.width/2;
    self.headImageView.layer.masksToBounds = YES;
    self.headImageView.image = [UIImage imageNamed:@"zc_photo_bg"];
    [backImageView addSubview:self.headImageView];
    
    rect = self.headImageView.frame;
    rect.origin.y = self.headImageView.bottom + 15;
    rect.size.height = 25 ;
    self.uploadIconButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.uploadIconButton.frame = rect;
    self.uploadIconButton.layer.cornerRadius = 5.0f;
    self.uploadIconButton.backgroundColor = RGB(239.0f, 115.0f, 10.0f);
    [self.uploadIconButton setTitle:@"上传头像" forState:UIControlStateNormal];
    [self.uploadIconButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.uploadIconButton.titleLabel.font = [UIFont systemFontOfSize:14.0f];
    self.uploadIconButton.hidden = YES;
    [backImageView addSubview:self.uploadIconButton];
    
    [self.uploadIconButton addTarget:self action:@selector(onClickUploadIcon:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)initContentView
{
    CGRect rect = CGRectMake(10, 190, self.view.width, 36);
    UILabel *label = [[UILabel alloc] initWithFrame:rect];
    label.backgroundColor = [UIColor clearColor];
    label.text = @"基本信息";
    label.textColor = [UIColor blackColor];
    label.font = [UIFont boldSystemFontOfSize:20.0f];
    [self.infoScrollView addSubview:label];
    
    rect = CGRectMake(0, label.height - 0.5f, self.view.width - 10, 0.5f);
    UIView *lineView = [[UIView alloc] initWithFrame:rect];
    lineView.backgroundColor = [UIColor grayColor];
    lineView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
    [label addSubview:lineView];
    
    rect = CGRectMake(label.width - 46, label.top, 36, 36);
    self.editButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.editButton.frame = rect;
    [self.editButton setTitle:@"编辑" forState:UIControlStateNormal];
    [self.editButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    self.editButton.titleLabel.font = [UIFont systemFontOfSize:16.0f];
    [self.infoScrollView addSubview:self.editButton];
    [self.editButton addTarget:self action:@selector(onClickEditButton:) forControlEvents:UIControlEventTouchUpInside];
    
    rect = CGRectMake(0, label.bottom, self.view.width, 40);
    self.addressView = [[UIView alloc] initWithFrame:rect];
    [self.infoScrollView addSubview:self.addressView];
    
    rect.origin.y += 40;
    self.sexView = [[UIView alloc] initWithFrame:rect];
    [self.infoScrollView addSubview:self.sexView];
    
    rect.origin.y += 40;
    self.signView = [[UIView alloc] initWithFrame:rect];
    [self.infoScrollView addSubview:self.signView];
    
    rect.origin.y += 40;
    self.weightView = [[UIView alloc] initWithFrame:rect];
    [self.infoScrollView addSubview:self.weightView];
    
    rect.origin.y += 40;
    self.heightView = [[UIView alloc] initWithFrame:rect];
    [self.infoScrollView addSubview:self.heightView];
    
    rect = CGRectMake(10, 10, 55, 20);
    UILabel *tagLabel = [[UILabel alloc] initWithFrame:rect];
    tagLabel.backgroundColor = [UIColor clearColor];
    tagLabel.textColor = [UIColor grayColor];
    tagLabel.font = [UIFont systemFontOfSize:18.0f];
    tagLabel.text = @"所在地";
    [self.addressView addSubview:tagLabel];
    
    tagLabel = [[UILabel alloc] initWithFrame:rect];
    tagLabel.backgroundColor = [UIColor clearColor];
    tagLabel.textColor = [UIColor grayColor];
    tagLabel.font = [UIFont systemFontOfSize:18.0f];
    tagLabel.text = @"性\t别";
    [self.sexView addSubview:tagLabel];
    
    tagLabel = [[UILabel alloc] initWithFrame:rect];
    tagLabel.backgroundColor = [UIColor clearColor];
    tagLabel.textColor = [UIColor grayColor];
    tagLabel.font = [UIFont systemFontOfSize:18.0f];
    tagLabel.text = @"签\t名";
    [self.signView addSubview:tagLabel];
    
    tagLabel = [[UILabel alloc] initWithFrame:rect];
    tagLabel.backgroundColor = [UIColor clearColor];
    tagLabel.textColor = [UIColor grayColor];
    tagLabel.font = [UIFont systemFontOfSize:18.0f];
    tagLabel.text = @"体\t重";
    [self.weightView addSubview:tagLabel];
    
    tagLabel = [[UILabel alloc] initWithFrame:rect];
    tagLabel.backgroundColor = [UIColor clearColor];
    tagLabel.textColor = [UIColor grayColor];
    tagLabel.font = [UIFont systemFontOfSize:18.0f];
    tagLabel.text = @"身\t高";
    [self.heightView addSubview:tagLabel];
    
    rect = CGRectMake(10, self.addressView.height - 0.5f, self.addressView.width - 10, 0.5f);
    lineView = [[UIView alloc] initWithFrame:rect];
    lineView.backgroundColor = [UIColor grayColor];
    lineView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
    [self.addressView addSubview:lineView];
    
    lineView = [[UIView alloc] initWithFrame:rect];
    lineView.backgroundColor = [UIColor grayColor];
    lineView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
    [self.sexView addSubview:lineView];
    
    lineView = [[UIView alloc] initWithFrame:rect];
    lineView.backgroundColor = [UIColor grayColor];
    lineView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
    [self.signView addSubview:lineView];
    
    lineView = [[UIView alloc] initWithFrame:rect];
    lineView.backgroundColor = [UIColor grayColor];
    lineView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
    [self.weightView addSubview:lineView];
    
    lineView = [[UIView alloc] initWithFrame:rect];
    lineView.backgroundColor = [UIColor grayColor];
    lineView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
    [self.heightView addSubview:lineView];
    
    rect = CGRectMake(tagLabel.right + 10, 10, self.view.width - tagLabel.right - 20, 20);
    NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:CGSizeMake(rect.size.width, CGFLOAT_MAX)];
    NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
    NSTextStorage *textStorage = [[NSTextStorage alloc] init];
    [textStorage addLayoutManager:layoutManager];
    [layoutManager addTextContainer:textContainer];
    
    self.addressTextView = [[UITextView alloc] initWithFrame:rect textContainer:textContainer];
    self.addressTextView.textContainerInset = UIEdgeInsetsZero;
    self.addressTextView.delegate = self;
    self.addressTextView.editable = NO;
    self.addressTextView.textColor = [UIColor blackColor];
    self.addressTextView.font = [UIFont systemFontOfSize:18.0f];
    self.addressTextView.backgroundColor = [UIColor clearColor];
    [self.addressView addSubview:self.addressTextView];
    
    rect.size.width = 20;
    self.sexImageView = [[UIImageView alloc] initWithFrame:rect];
    [self.sexView addSubview:self.sexImageView];
    
    rect = self.addressTextView.frame;
    NSTextContainer *signTextContainer = [[NSTextContainer alloc] initWithSize:CGSizeMake(rect.size.width, CGFLOAT_MAX)];
    NSLayoutManager *signLayoutManager = [[NSLayoutManager alloc] init];
    NSTextStorage *signTextStorage = [[NSTextStorage alloc] init];
    [signTextStorage addLayoutManager:signLayoutManager];
    [signLayoutManager addTextContainer:signTextContainer];
    
    self.signTextView = [[UITextView alloc] initWithFrame:rect textContainer:signTextContainer];
    self.signTextView.textContainerInset = UIEdgeInsetsZero;
    self.signTextView.delegate = self;
    self.signTextView.editable = NO;
    self.signTextView.textColor = [UIColor blackColor];
    self.signTextView.font = [UIFont systemFontOfSize:18.0f];
    [self.signView addSubview:self.signTextView];
    
    self.weightTextField = [[UITextField alloc] initWithFrame:rect];
    self.weightTextField.delegate = self;
    self.weightTextField.enabled = NO;
    self.weightTextField.textColor = [UIColor blackColor];
    self.weightTextField.font = [UIFont systemFontOfSize:16.0f];
    self.weightTextField.keyboardType = UIKeyboardTypeNumberPad;
    [self.weightView addSubview:self.weightTextField];
    
    self.heightTextField = [[UITextField alloc] initWithFrame:rect];
    self.heightTextField.delegate = self;
    self.heightTextField.enabled = NO;
    self.heightTextField.textColor = [UIColor blackColor];
    self.heightTextField.font = [UIFont systemFontOfSize:16.0f];
    self.heightTextField.keyboardType = UIKeyboardTypeNumberPad;
    [self.heightView addSubview:self.heightTextField];
    
    self.contentViewArray = [NSMutableArray array];
    [self.contentViewArray addObject:self.addressView];
    [self.contentViewArray addObject:self.sexView];
    [self.contentViewArray addObject:self.signView];
    [self.contentViewArray addObject:self.weightView];
    [self.contentViewArray addObject:self.heightView];
    
    self.sexButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.sexButton.frame = self.sexView.bounds;
    self.sexButton.backgroundColor = [UIColor clearColor];
    [self.sexButton addTarget:self action:@selector(onClickSexButton:) forControlEvents:UIControlEventTouchUpInside];
    self.sexButton.hidden = YES;
    [self.sexView addSubview:self.sexButton];
}

- (void)onClickUploadIcon:(id)sender
{
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"相册",@"拍照", nil];
    actionSheet.tag = 100;
    [actionSheet showInView:self.view];
}

- (void)onClickSexButton:(id)sender
{
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"请选择性别" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"男",@"女", nil];
    actionSheet.tag = 99;
    [actionSheet showInView:self.view];
}

- (void)onClickEditButton:(UIButton *)sender
{
    if ([sender.titleLabel.text isEqualToString:@"编辑"]) {
        self.addressTextView.editable = YES;
        self.signTextView.editable = YES;
        self.weightTextField.enabled = YES;
        self.heightTextField.enabled = YES;
        self.uploadIconButton.hidden = NO;
        [sender setTitle:@"完成" forState:UIControlStateNormal];
        self.sexButton.hidden = NO;
    }else {
        
        [[UIApplication sharedApplication].keyWindow endEditing:YES];
        
        [self changeUserInfo];
        
        self.addressTextView.editable = NO;
        self.signTextView.editable = NO;
        self.weightTextField.enabled = NO;
        self.heightTextField.enabled = NO;
        self.uploadIconButton.hidden = YES;
        self.sexButton.hidden = YES;
        [sender setTitle:@"编辑" forState:UIControlStateNormal];
    }
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (actionSheet.tag == 99) {
        if (buttonIndex == 0) {
            self.sex = 0;
        }else if (buttonIndex == 1) {
            self.sex = 1;
        }
        [self updateUserValue];
    }else {
        if (buttonIndex == 0) {
            [self pickPhoto];
        }else if (buttonIndex == 1) {
            [self takePhoto];
        }
    }
}

- (void)updateUserValue
{
    CurrentUser *currentUser = [CurrentUser shareInstance];
    [self.headImageView sd_setImageWithURL:[NSURL URLWithString:currentUser.icon] placeholderImage:[UIImage imageNamed:@"zc_photo_bg"]];
    
    self.addressTextView.text = currentUser.address;
    
    NSString *imageName = self.sex == 1 ? @"female_icon" : @"male_icon";
    self.sexImageView.image = [UIImage imageNamed:imageName];
    
    self.signTextView.text = currentUser.signature;
    
    self.weightTextField.text = [[NSString alloc] initWithFormat:@"%.0fkg",currentUser.weight];
    
    self.heightTextField.text = [[NSString alloc] initWithFormat:@"%.0fcm",currentUser.height];
}

- (void)updateContentFrame
{
    self.addressTextView.height = [self getTextViewHeight:self.addressTextView];
    self.addressView.height = self.addressTextView.height + 20;
    
    self.signTextView.height = [self getTextViewHeight:self.signTextView];
    self.signView.height = self.signTextView.height + 20;
    
    for (NSInteger i = 1; i < self.contentViewArray.count; i++) {
        UIView *currentView = [self.contentViewArray objectAtIndex:i];
        UIView *preView = [self.contentViewArray objectAtIndex:i-1];
        currentView.top = preView.bottom;
    }
    
    UIView *lastView = self.contentViewArray.lastObject;
    self.infoScrollView.contentSize = CGSizeMake(self.view.width, lastView.bottom + 20);
}

#pragma mark - keyboard
- (void)onkeyboardChange:(NSNotification *)notification
{
    CGRect rect = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    self.infoScrollView.contentInset = UIEdgeInsetsMake(0, 0, rect.size.height, 0);
    
    self.infoScrollView.contentOffset = CGPointMake(0, 190);
}

- (void)onkeyboardHide:(NSNotification *)notification
{
    self.infoScrollView.contentInset = UIEdgeInsetsZero;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if (textField == self.weightTextField) {
        textField.text = [self.weightTextField.text substringToIndex:self.weightTextField.text.length - 2];
    } else if (textField == self.heightTextField) {
        textField.text = [self.heightTextField.text substringToIndex:self.heightTextField.text.length - 2];
    }
    
    return YES;
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    if (textField == self.weightTextField) {
        textField.text = [NSString stringWithFormat:@"%@kg", textField.text];
    } else if (textField == self.heightTextField) {
        textField.text = [NSString stringWithFormat:@"%@cm", textField.text];
    }
    
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

- (void)textViewDidChange:(UITextView *)textView
{
    [self updateContentFrame];
}

#pragma mark - help
- (CGFloat)getTextViewHeight:(UITextView *)textView
{
    CGFloat height = 0.0f;
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0f) {
        CGRect textFrame=[[textView layoutManager] usedRectForTextContainer:[textView textContainer]];
        height = textFrame.size.height + 2;
    }else {
        
        height = textView.contentSize.height;
    }
    return height;
}

#pragma mark - 图片
- (void)takePhoto
{
    BOOL rearCameraAvailable = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];//前
    BOOL frontCameraAvailable = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
    
    if (!rearCameraAvailable && !frontCameraAvailable) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"此设备相机不可用" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        return;
    }
    
    NSUInteger sourceType = 0;//初始化调用相机相册的方法
    sourceType = UIImagePickerControllerSourceTypeCamera;//调用相册
    
    UIImagePickerController * imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsEditing = YES;
    imagePickerController.sourceType = sourceType;
    [self presentViewController:imagePickerController animated:YES completion:nil];
}

- (void)pickPhoto
{
    NSUInteger sourceType = 0;//初始化调用相机相册的方法
    sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;//调用相机
    
    UIImagePickerController * imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsEditing = YES;
    imagePickerController.sourceType = sourceType;
    [self.navigationController presentViewController:imagePickerController animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //要上传的图片
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    
    [self uploadIcomImage:image];
    
    [picker dismissViewControllerAnimated:YES completion:nil];

}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - net
- (void)changeUserInfo
{
    NSString *address = self.addressTextView.text;
    NSString *sign = self.signTextView.text;
    NSString *weightText = self.weightTextField.text;
    NSString *heightText = self.heightTextField.text;
    CGFloat weight = weightText.floatValue;
    CGFloat height = heightText.floatValue;
    
    [UserNet updateUserWithAddress:address sex:self.sex signature:sign friendCheck:NO height:height weight:weight successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        BOOL success = [[responseObject objectForKey:@"success"] boolValue];
        if (success) {
            CurrentUser *user = [CurrentUser shareInstance];
            user.sex = self.sex;
            user.signature = sign;
            user.weight = weight;
            user.height = height;
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self updateUserValue];
                [self showText:@"修改成功！" time:2];
            });
        } else {
            NSString *message = [responseObject objectForKey:@"message"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:message time:2];
            });
        }
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self showText:@"网络连接失败" time:2];
        });
    }];
}

- (void)uploadIcomImage:(UIImage *)image
{
    NSData *data = UIImageJPEGRepresentation(image, 0.3f);
    @weakify(self);
    [UserNet uploadIconWithIconData:data successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        @strongify(self);
        BOOL success = [[responseObject objectForKey:@"success"] boolValue];
        if (success) {
            [CurrentUser shareInstance].icon = [responseObject objectForKey:@"data"];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:@"上传头像成功！" time:2];
                self.headImageView.image = image;
            });
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"User_Info_Changed" object:nil userInfo:nil];
        } else {
            NSString *message = [responseObject objectForKey:@"message"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:message time:2];
            });
        }
        
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self showText:@"网络连接失败" time:2];
        });
    }];
}
@end
